package com.zsy._15单例模式;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 枚举实现单例
 *
 * @author: zhangshuaiyin
 * @date: 2021/10/4 23:26
 */
public enum Single05Enum {

    /**
     * 枚举单例不会被反射破坏，会抛出异常：IllegalArgumentException Cannot reflectively create enum objects
     * <p>
     * 枚举类的Class文件反编译为java代码，默认有一个两个参数的构造器，当反射调用这个构造器创建多个对象时就会抛出异常，保证单例
     */
    INSTANCE;

    public Single05Enum getInstance() {
        return INSTANCE;
    }

    static class Test {
        public static void main(String[] args) throws NoSuchMethodException,
                IllegalAccessException, InvocationTargetException, InstantiationException {
            Single05Enum instance1 = Single05Enum.INSTANCE;
            Constructor<Single05Enum> declaredConstructor =
                    Single05Enum.class.getDeclaredConstructor(String.class, int.class);
            declaredConstructor.setAccessible(true);
            Single05Enum instance2 = declaredConstructor.newInstance();
            System.out.println(instance1.equals(instance2));
        }
    }
}
